package com.hhf.riceshopping.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.hhf.common.constant.AuthServerConstant;
import com.hhf.common.utils.R;
import com.hhf.common.vo.MemberRespVo;
import com.hhf.riceshopping.auth.feign.MemberFeignService;
import com.hhf.riceshopping.auth.vo.UserLoginVo;
import com.netflix.ribbon.proxy.annotation.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class LoginController {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute==null){
            //没登陆
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }

    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登陆
        R login = memberFeignService.login(vo);
        if (login.getCode()==0){
            //成功
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            //登陆成功把用户信息放到session中
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            //重定向
            return "redirect:http://gulimall.com";
        }else {
            Map<String, String> errors = new ConcurrentHashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
